<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">

<head>
    <!-- 引用模板 Header -->
    <div th:insert="bg/publicHead :: publicHead(${pageName})"></div>
    <!-- [ Header ] end -->

    <link rel="stylesheet" href="/css/base.css" type="text/css" />
    <script src="/js/jquery-1.9.1.min.js" type="text/javascript"></script>
    <script src="/js/sweetalert.min.js" type="text/javascript" charset="UTF-8"></script>
    <script src="/js/stroage.js" type="text/javascript" charset="UTF-8"></script>
    <script src="/js/comm.js" type="text/javascript" charset="UTF-8"></script>

    <script th:inline="javascript">
        window.onerror=function(){return true;};
        var ServerIP=[(${ServerIP!=null?'"'+ServerIP+'"':'"'+'"'})];
        var mainId=null;
        var sp_products=[(${(products!=null && products!='')?products:'null'})]; //产品数据
        var sp_productNo=null;
        var sp_curUploadImageUrl=null;
        var maxFileSize=500; //KB
        var isUpdate=false;
        //记录组件状态名称
        var components=[
            "sp_productstitle",
            "sp_size",
            "sp_weight",
            "sp_materials",
            "sp_colors",
            "sp_functions",
            "sp_character",
            "sp_productstag",
            "sp_productssell",
            "sp_productsstore",
            "sp_productsdesc",
            "sp_productoriginprice",
            "sp_productsdiscountprice",
            "sp_productsfactory",
        ];
        $(document).ready(function() {

            //初始化数据
            $(".selectUpload").css("display","block");
            $(".uploadedimg").css("display","none");


            //保存input组件输入状态
            var storeInput=(arg)=>{
                for (let i = 0; i < arg.length; i++) {
                    $("."+arg[i]).blur(function(){
                        myStorage.setItem(arg[i],$(this).val());
                    });
                }
            }
            var restoreInput=(arg)=>{
                for (let i = 0; i < arg.length; i++) {
                    $("."+arg[i]).val(myStorage.getItem(arg[i]));
                }
            }
            var removestoreInput=(arg)=>{
                for (let i = 0; i < arg.length; i++) {
                    myStorage.removeItem(arg[i]);
                    $("."+arg[i]).val("");
                }
            }

            //还原组件状态
            restoreInput(components);

            //注册侦听组件输入状态
            storeInput(components);

            //发布成功清除所有缓存
            var clearAllStores=(flag)=>{
                removestoreInput(components);
                if(flag==true){
                    window.location.href=window.location.href;
                }
            }



            //读取数据到编辑器
            if(sp_products!=null){
                console.log(sp_products);
                $(".h4").text("添加产品规格");
                //先清空一次所有缓存
                //主产品id=
                mainId=sp_products.id;
                //主产品图
                $(".mainimg").attr("src",sp_products.productimg);
                //主产品名称
                $(".mainp").text(sp_products.productname);
                //主产品型号
                sp_productNo=sp_products.productno;
                $(".mainNo").text(sp_productNo);
            }





            //还原select组件状态
            var restoreSelectInput=()=>{
                    if(isUpdate==false){
                        //还原封面图
                        if(myStorage.getItem("sp_curUploadImageUrl")!=null && myStorage.getItem("sp_curUploadImageUrl")!=""){
                            sp_curUploadImageUrl=myStorage.getItem("sp_curUploadImageUrl");
                            $(".uploadedimg").css("display","block");
                            $(".uploadedimg img").attr("src",sp_curUploadImageUrl); //显示刚刚上传成功的图片
                        }
                    } //isUpdate End
            }
            restoreSelectInput();


            //检查图片的大小
            var checkImageSize=(targetObj,curFile,flag)=>{
                console.log("当前检查文件",curFile,"文件大小:",curFile.size)
                if((curFile.size/1000)>maxFileSize){
                    targetObj.val("");
                    if(flag==true){
                        swal("上传失败！图片不能大于"+maxFileSize+"KB", "请压缩后上传", "error");
                    }
                    return false;
                }
                return true;
            }



            //封面图上传
            $("#uploadPhotoFile").change(async function(){
                var file = this.files[0];
                if(sp_productNo===null){
                    alert("产品编号异常");
                    return;
                }
                //检测文件大小
                if(checkImageSize($(this),file,true)===false){
                    return;
                }
                var formData = new FormData();
                formData.append("multipartFile",file);
                //console.log("准备上传参数信息:",formData,formData.forEach(value => console.log(value)))
                var res=await SyncAjaxRequest(ServerIP+'api/OssUploadImage',formData,sp_productNo);
                console.log("文件上传结果===>:",res);
                if(res.code===200){
                    sp_curUploadImageUrl=res.result;
                    myStorage.setItem("sp_curUploadImageUrl",sp_curUploadImageUrl); //设置缓存
                    $(".uploadedimg img").attr("src",sp_curUploadImageUrl); //显示刚刚上传成功的图片
                    $(this).val(""); //重置组件状态
                    swal("图片上传成功", "图片已上传", "success");
                    $(".selectUpload").css("display","none");
                    $(".uploadedimg").css("display","block");
                }else{
                    console.log("图片上传失败:",res.result); //失败原因
                    if(res.result!=null && res.result.indexOf("Prefix string too short")!=-1){
                        alert("图片名称太短 上传失败");
                    }else{
                        alert(res.msg);
                    }
                    sp_curUploadImageUrl="";
                    myStorage.removeItem("sp_curUploadImageUrl"); //清除缓存
                    $(".selectUpload").css("display","block");
                    $(".uploadedimg").css("display","none");
                }
            });



            //发布&更新
            $(".addBtn").click(async function(){

                if(sp_curUploadImageUrl===null){
                    swal("请上传封面图", "至少上传一张产品封面图", "error");
                    return;
                }
                if(mainId===null){
                    swal("主产品id不存在", "请检查", "error");
                    return;
                }

                //必填字段
                var sptitle=$(".sp_productstitle").val();
                var spdesc=$(".sp_productsdesc").val();
                var spprice=$(".sp_productoriginprice").val();
                var spdiscount=$(".sp_productsdiscountprice").val();
                var spproductsstore=$(".sp_productsstore").val();
                var spsellnum=$(".sp_productssell").val();

                //非必填字段
                var spsize=$(".sp_size").val();
                var spweight=$(".sp_weight").val();
                var spmaterials=$(".sp_materials").val();
                var spcolors=$(".sp_colors").val();
                var spfunctions=$(".sp_functions").val();
                var spcharacter=$(".sp_character").val();
                var sptags=$(".sp_productstag").val();
                var spproductsfactory=$(".sp_productsfactory").val();

                if(/\S/.test(sptitle)===false){
                    swal("请输入产品标题", "产品标题未设置", "error");
                    return;
                }
                if(/\S/.test(spdesc)===false){
                    swal("请填写使用说明", "使用说明未设置", "error");
                    return;
                }
                if(/\S/.test(spprice)===false){
                    swal("请输入产品原价", "请设置产品原价", "error");
                    return;
                }
                if(/^\d+$/.test(spprice)===false){
                    swal("原价为数字", "请输入数字", "error");
                    return;
                }
                if(/\S/.test(spdiscount)===false){
                    swal("请输入产品折扣价", "请设置产品折扣价", "error");
                    return;
                }
                if(/^\d+$/.test(spdiscount)===false){
                    swal("折扣价为数字", "请输入数字", "error");
                    return;
                }
                if(/\S/.test(spsellnum)===false){
                    swal("请输入已售数量", "请设置已售数量", "error");
                    return;
                }
                if(/^\d+$/.test(spsellnum)===false){
                    swal("已售数量为数字", "请输入数字", "error");
                    return;
                }
                if(/\S/.test(spproductsstore)===false){
                    swal("请输入产品库存", "请设置产品库存", "error");
                    return;
                }
                if(/^\d+$/.test(spproductsstore)===false){
                    swal("产品库存为数字", "请输入数字", "error");
                    return;
                }
                if (confirm("是否发布产品?")) {
                    var addData={
                        mainpid:mainId,
                        spname:$.trim(sptitle),
                        spphoto:sp_curUploadImageUrl,
                        sptype:$.trim(sp_productNo), //产品型号
                        spdesc:$.trim(spdesc),
                        sporiginprice:parseFloat(spprice),
                        spdiscountprice:parseFloat(spdiscount),
                        spstore:parseInt(spproductsstore),
                        spselled:parseInt(spsellnum),
                        spfactory:$.trim(spproductsfactory)===''?'自营':$.trim(spproductsfactory),
                    };
                    //追加更新字段
                    if(isUpdate==true) addData.id=sp_products.id;
                    //追加非必填字段
                    if(/\S/.test(spsize)===true) addData.spsize=spsize;
                    if(/\S/.test(spweight)===true) addData.spweight=spweight;
                    if(/\S/.test(spmaterials)===true) addData.spmaterials=spmaterials;
                    if(/\S/.test(spcolors)===true) addData.spcolor=spcolors.replace(/["，"]+/g,","); //将中文格式逗号变为英文逗号
                    if(/\S/.test(spfunctions)===true) addData.spfunction=spfunctions;
                    if(/\S/.test(spcharacter)===true) addData.spcharacter=spcharacter;
                    if(/\S/.test(sptags)===true) addData.sptags=sptags.replace(/["，"]+/g,",");

                    console.log("上传参数:",addData);
                    //return;

                    if(addData!=null){
                        var apiUrl=null;
                        if(isUpdate==false){
                            apiUrl="/api/addProductSpecification";
                        }else{ //更新模式
                            apiUrl="/api/updateProductSpecification";
                        }
                        if(apiUrl==null){
                            alert("apiUrl不能为空");
                            return;
                        }
                        var res=await SyncJson(apiUrl,addData);
                        if(res.code===200){
                            if(isUpdate==false) {
                                alert("产品发布成功");
                            }else{
                                alert("商品更新成功");
                            }
                            removestoreInput(components); //历史记录值
                            clearAllStores(true); //清空所有缓存
                        }
                    }
                }
            });


            //重置
            $(".resetBtn").click(function(){
                if (confirm("是否清空重置?")) {
                    clearAllStores(true);
                }
            });

        }); //document.ready End


    </script>
</head>

<!-- background:url('/bgTemplate/image/body-bg-7.jpg'); -->
<body class="bodybg">
<!-- [ Main Content ] start -->
<div class="contain">
    <h4 class="h4">添加产品规格</h4>
    <div class="doctors">
        <div class="tables">
            <div class="text">主产品图:</div>
            <div style="display:block;">
                <div class="input"><img class="mainimg" src="" style="width:100px; height:100px;" /></div>
            </div>
        </div>
        <div class="tables">
            <div class="text">主产品:</div>
            <div class="input mainp"></div>
        </div>
        <div class="tables">
            <div class="text">编号/型号:</div>
            <div class="input mainNo"></div>
        </div>
        <div class="tables">
            <div class="text"><span>*</span> 规格封面图:</div>
            <div style="display:block;">
                <div class="input uploadedimg" style="display:none;"><img src="" /></div>
                <div class="input selectUpload" style="margin-top:5px;"> <input id="uploadPhotoFile" type="file" accept="image/*"  /></div>
            </div>
        </div>
        <div class="tables">
            <div class="text"><span>*</span> 规格标题:</div>
            <div class="input"><input type="text" class="sp_productstitle" maxlength="30"></div>
        </div>
        <div class="tables">
            <div class="text"><span>*</span> 使用说明:</div>
            <div class="input"><input type="text" class="sp_productsdesc" maxlength="200" placeholder="使用说明200字内"></div>
        </div>
        <div class="tables">
            <div class="text">规格尺寸:</div>
            <div class="input"><input type="text" class="sp_size" maxlength="30"></div>
        </div>
        <div class="tables">
            <div class="text">规格重量:</div>
            <div class="input"><input type="text" class="sp_weight" maxlength="20"></div>
        </div>
        <div class="tables">
            <div class="text">规格材料:</div>
            <div class="input"><input type="text" class="sp_materials" maxlength="30"></div>
        </div>
        <div class="tables">
            <div class="text">规格颜色:</div>
            <div class="input"><input type="text" class="sp_colors" maxlength="100" placeholder="多个标签用逗号，分割 如:白色,黑色,黄色"></div>
        </div>
        <div class="tables">
            <div class="text">功能:</div>
            <div class="input"><input type="text" class="sp_functions" maxlength="100"></div>
        </div>
        <div class="tables">
            <div class="text">特性:</div>
            <div class="input"><input type="text" class="sp_character" maxlength="100"></div>
        </div>
        <div class="tables">
            <div class="text">标签:</div>
            <div class="input"><input type="text" class="sp_productstag" maxlength="100" placeholder="多个标签用逗号，分割 如:电器,五金"></div>
        </div>
        <div class="tables">
            <div class="text"><span>*</span> 原价:</div>
            <div class="input"><input type="text" class="sp_productoriginprice" value="0"></div>
        </div>
        <div class="tables">
            <div class="text"><span>*</span> 折扣价:</div>
            <div class="input"><input type="text" class="sp_productsdiscountprice" value="0"></div>
        </div>
        <div class="tables">
            <div class="text"><span>*</span> 已售:</div>
            <div class="input"><input type="text" class="sp_productssell" value="0"></div>
        </div>
        <div class="tables">
            <div class="text"><span>*</span> 库存量:</div>
            <div class="input"><input type="text" class="sp_productsstore" value="10"></div>
        </div>
        <div class="tables">
            <div class="text">厂家名称:</div>
            <div class="input"><input type="text" class="sp_productsfactory" value="自营"></div>
        </div>
        <div class="tables" style="border-bottom:0px; margin-top:20px;">
            <div class="text sbtn">
                <a class="addBtn">添加</a>
                <a class="resetBtn">重置</a>
            </div>
            <div class="input"></div>
        </div>
    </div>
</div>
<!--中间 End -->
</body>

</html>


